package com.bawei.image.glide

import android.content.Context
import android.os.Environment
import com.bumptech.glide.Glide
import com.bumptech.glide.Registry
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.module.LibraryGlideModule
import okhttp3.Cache
import okhttp3.OkHttpClient
import java.io.File
import java.io.InputStream

/**
 * 作者：Jason
 * 日期：2023/11/15
 * 描述：利用OkHttpClient设置网络缓存目录
 */
@GlideModule
class OkHttpModule : LibraryGlideModule() {

    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
        //创建一个OkHttpClient来替换Glide中默认的OkHttp的实现
        val builder = OkHttpClient.Builder()
        //SD卡存储目录
        val dirFile = Environment.getExternalStorageDirectory()
        if (dirFile.exists()) {
            val cacheDir = "${dirFile.absolutePath}/cacheImages"
            var cacheFile = File(cacheDir)
            if (!cacheFile.exists()) {
                cacheFile = File(cacheDir)
            }
            //设置网络缓存文件及大小
            builder.cache(Cache(cacheFile, 250 * 1024 * 1024))
        } else {
            val cacheDir = "${context.externalCacheDir?.absolutePath}/glideImages"
            var cacheFile = File(cacheDir)
            if (!cacheFile.exists()) {
                cacheFile = File(cacheDir)
            }
            //设置网络缓存文件及大小
            var cacheSize = 50 * 1024 * 1024L
            context.externalCacheDir?.totalSpace?.let {
                cacheSize = it / 4L
            }
            builder.cache(Cache(cacheFile, cacheSize))
        }

        //使用注册机替换默认OkHttpClient
        registry.replace(
            GlideUrl::class.java,
            InputStream::class.java,
            OkHttpUrlLoader.Factory(builder.build())
        )
    }

}